<template>
  <div class="app-container">
    <el-form :model="queryParams" :rules="rules" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px"
             onsubmit="return false;">
      <el-form-item label="数据库名" prop="condition[dbName|like]">
        <el-input
          v-model="queryParams['condition[dbName|like]']"
          placeholder="请输入数据库名"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleExport"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="typeList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="描述" align="left" prop="dbDesc" :show-overflow-tooltip="true"/>
      <el-table-column label="数据库" align="left" width="300" prop="dbName" :show-overflow-tooltip="true"/>
      <el-table-column label="服务器IP" align="left" prop="dbUrl"/>
      <el-table-column label="端口" align="left" prop="dbPort"/>
      <el-table-column label="类型" align="left" prop="dbType"/>
      <el-table-column label="用户名" align="left" prop="dbUsername"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="300">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改
          </el-button>
          <el-button
            type="text"
            size="small"
            icon="el-icon-refresh"
            @click="handleSynchDb(scope.row)"
          >同步
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="fas fa-feather"
            @click="handleGenCode(scope.row)"
          >代码生成
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改数据库类型对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">

        <!-- <el-form-item label="描述" prop="dbDesc">
          <el-input v-model="form.dbDesc" placeholder="数据库描述"/>
        </el-form-item> -->

        <el-form-item label="名称" prop="dbName">
          <el-input v-model="form.dbName" placeholder="数据库名称"/>
        </el-form-item>
        <el-form-item label="IP" prop="dbUrl">
          <el-input v-model="form.dbUrl" placeholder="服务器IP"/>
        </el-form-item>

        <el-form-item label="类型" prop="dbType">
          <el-select v-model="form.dbType" placeholder="请选择数据库类型">
            <el-option label="MySQL" :value="form.dbType" />
          </el-select>
        </el-form-item>

        <el-form-item label="端口" prop="dbPort">
          <el-input v-model="form.dbPort" placeholder="连接端口"/>
        </el-form-item>
        <el-form-item label="用户名" prop="dbUsername">
          <el-input v-model="form.dbUsername" placeholder="数据库用户名"/>
        </el-form-item>
        <el-form-item label="密码" prop="dbPasswd">
          <el-input type="password" v-model="form.dbPasswd" placeholder="数据库密码"/>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 获取构建信息 -->
    <el-dialog title="构建信息" :model="genForm" :visible.sync="generatorFormVisible" width="800px" append-to-body>
      <el-form ref="genForm" :model="genForm" :rules="genRules" label-width="100px">
        <el-form-item label="工程包路径" prop="packagePath">
          <el-input v-model="genForm.packagePath" placeholder="com.alinesno.cloud.test" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="模块名" prop="moduleName">
          <el-input v-model="genForm.moduleName" placeholder="test/moduleName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="作者名" prop="author">
          <el-input v-model="genForm.author" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="生成类型" prop="createType">
          <el-select v-model="genForm.createType" placeholder="请选择生成类型">
            <el-option label="前后端分离" :value="genForm.createType" selected></el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="generatorFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitGenForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    addCasLoginRecord, checkDbConfig,
    delCasLoginRecord,
    exportCasLoginRecord,
    getCasLoginRecord,
    listCasLoginRecord,
    syncDataBase,
    updateCasLoginRecord
  } from "./api";
  import {downLoadZip} from "alinesno-ui/src/utils/zipdownload";

  export default {
    name: "Type",
    components: {},
    data() {
      return {
        // 选中数据库ID
        selectDbId: '',
        // 遮罩层
        loading: true,
        // 导出遮罩层
        exportLoading: false,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 数据库类型表格数据
        typeList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 构建信息表单
        generatorFormVisible: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          dbDesc: null,
          'condition[dbName|like]': null,
          dbName: null,
          dbUrl: null,
          dbPort: null,
          dbUsername: null,
          dbPasswd: null,
          dbType: null,
        },
        // 表单参数
        form: {
          dbType: 'MySQL' ,
        },
        genForm: {
          packagePath: '',
          moduleName: '',
          author: '',
          createType: 'front'
        },
        // 表单校验
        rules: {
          dbDesc: {required: true, message: '请输入数据库描述', trigger: 'blur'},
          dbName: {required: true, message: '请输入数据库名', trigger: 'blur'},
          dbUrl: {required: true, message: '请输入连接信息', trigger: 'blur'},

          dbPort: {required: true, message: '请输入端口信息', trigger: 'blur'},

          dbUsername: {required: true, message: '请输入连接用户名', trigger: 'blur'},

          dbPasswd: {required: true, message: '请输入连接密码', trigger: 'blur'},

          // dbType: {required: true, message: '请选择数据库类型', trigger: 'blur'},

        },
        genRules:
          {
            packagePath: [
              {required: true, message: '请输入工程包路径', trigger: 'blur'},
              {
                pattern: /[a-zA-Z]+[0-9a-zA-Z_]*(\.[a-zA-Z]+[0-9a-zA-Z_]*)*/,
                message: '包名格式不正确,如 com.alinesno.cloud.student.manager',
                trigger: 'blur'
              }

            ],
            moduleName:
              [
                {required: true, message: '模块名称不能为空', trigger: 'blur'},
              ],
            author:
              [
                {required: true, message: '作者名称不能为空', trigger: 'blur'},
              ],
            // createType:
            //   [
            //     {required: true, message: '生成类型不能为空', trigger: 'blur'},
            //   ],
          }
      }
        ;
    },
    created() {
      this.getList();
    },
    methods: {
      /** 查询数据库类型列表 */
      getList() {
        this.loading = true;
        listCasLoginRecord(this.queryParams).then(response => {
          this.typeList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: null,
          dbDesc: null,
          dbName: null,
          dbUrl: null,
          dbPort: null,
          dbUsername: null,
          dbPasswd: null,
          dbType: null,
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加数据库类型";
      },
      // 数据库生成代码
      handleGenCode(row) {
        this.generatorFormVisible = true
        this.selectDbId = row.id
        this.genForm.author =row.author;
        this.genForm.createType =row.createType;
        this.genForm.packagePath =row.packagePath;
        this.genForm.moduleName =row.moduleName;
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const id = row.id || this.ids
        getCasLoginRecord(id).then(response => {
          this.form = response.data;
          this.open = true;
          this.title = "修改数据库类型";
        });
      },
      /** 提交数据库代码生成按钮 */
      submitGenForm() {
        this.$refs["genForm"].validate(valid => {
          if (valid) {
            const packagePath = this.genForm.packagePath;
            const author = encodeURIComponent(this.genForm.author);
            const createType = this.genForm.createType;
            const moduleName = this.genForm.moduleName;

            const queryParams = 'id=' + this.selectDbId + '&packagePath=' + packagePath + '&author=' + author + '&createType=' + createType + '&moduleName=' + moduleName;
            const url = '/com/alinesno/cloud/initializr/codeGenertor/gen/genCodeByDb?' + queryParams;
            console.log('url = ' + url);

            this.generatorFormVisible = false;
            downLoadZip(url);

            this.$message('执行成功,正在生成代码请稍后…');
          }
        });
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            checkDbConfig(this.form).then(resp=>{
              if (resp.data.accepted){
                if (this.form.id != null) {
                  updateCasLoginRecord(this.form).then(response => {
                    this.msgSuccess("修改成功");
                    this.open = false;
                    this.getList();
                  });
                } else {
                  addCasLoginRecord(this.form).then(response => {
                    this.msgSuccess("新增成功");
                    this.open = false;
                    this.getList();
                  });
                }
              }else {
                  this.msgError(resp.msg)
              }
            })

          }
        });
      },
      /** 同步数据库操作 */
      handleSynchDb(row) {

        const dbName = row.dbName;
        const id = row.id;

        this.$confirm('确认要强制同步"' + dbName + '"表结构吗？', "提示", {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          const loading = this.$loading({
            lock: true,
            text: '正在同步中,大概1分钟,请稍等...',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          });
          syncDataBase(id).then(response => {
            loading.close();
            this.$message({
              type: 'success',
              message: '同步成功!'
            });
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消同步'
          });
        });

      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        this.$confirm('是否确认删除数据库类型编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function () {
          return delCasLoginRecord(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
      },
      /** 导出按钮操作 */
      handleExport() {
        const queryParams = this.queryParams;
        this.$confirm('是否确认导出所有数据库类型数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.exportLoading = true;
          return exportCasLoginRecord(queryParams);
        }).then(response => {
          this.download(response.msg);
          this.exportLoading = false;
        })
      }
    }
  };
</script>
